package com.dog.framework.mqtt;


import com.dog.framework.mqtt.component.DefaultMqttListener;
import com.dog.framework.mqtt.component.IMqttListener;
import com.dog.framework.mqtt.config.MqttClientProperties;
import com.dog.framework.mqtt.config.MqttConsumerProperties;
import com.dog.framework.mqtt.config.MqttProducerProperties;
import com.dog.framework.mqtt.domain.IotMessage;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * Mqtt自动配置
 * </p>
 *
 * @author liuxk
 * @since 2023/11/21
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.mqtt", name = "enabled", havingValue = "true")
@ComponentScan("com.dog.framework.mqtt")
@IntegrationComponentScan({"com.dog.framework.mqtt"})
@EnableConfigurationProperties({MqttClientProperties.class, MqttProducerProperties.class, MqttConsumerProperties.class})
public class RoboticsMqttAutoConfiguration {

    private static final Logger log = LoggerFactory.getLogger(RoboticsMqttAutoConfiguration.class);

    private static final byte[] WILL_DATA;

    static {
        WILL_DATA = "offline".getBytes();
    }

    @Value("${spring.profiles.active:native}")
    private String profile;

    @Autowired
    private MqttClientProperties clientProperties;

    @Autowired
    private MqttProducerProperties producerProperties;

    @Autowired
    private MqttConsumerProperties consumerProperties;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * MQTT out连接器选项
     *
     * @return {@link MqttConnectOptions}
     */
    @Bean
    @ConditionalOnMissingBean
    public MqttConnectOptions mqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，客户端断线时暂时不清除，直到超时注销
        // 这里设置为true表示每次连接到服务器都以新的身份连接
        options.setCleanSession(false);
        options.setAutomaticReconnect(true);
        // 配置最大不确定接收消息数量，默认值10，qos!=0 时生效
        options.setMaxInflight(600);
        // 配置mqtt服务端地址,登录账号和密码
        options.setUserName(clientProperties.getUsername());
        options.setPassword(clientProperties.getPassword().toCharArray());
        //客户端地址
        options.setServerURIs(new String[]{clientProperties.getUrl()});
        // 设置超时时间 单位为秒
        options.setConnectionTimeout(clientProperties.getTimeout());
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送心跳判断客户端是否在线，但这个方法并没有重连的机制
        options.setKeepAliveInterval(clientProperties.getKeepalive());
        // 设置“遗嘱”消息的话题，若客户端与服务器之间的连接意外中断，服务器将发布客户端的“遗嘱”消息。
//        options.setWill("willTopic", WILL_DATA, 2, false);
        return options;
    }

    /**
     * MQTT 客户端
     *
     * @return {@link MqttPahoClientFactory}
     */
    @Bean(name = "mqttClientFactory")
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(mqttConnectOptions());
        return factory;
    }

    /**
     * MQTT发布信息通道
     *
     * @return {@link MessageChannel}
     */
    @Bean
    public MessageChannel mqttOutboundChannel() {
        DirectChannel dc = new DirectChannel();
        dc.subscribe(mqttOutboundHandler());
        return dc;
    }


    /**
     * 配置Inbound入站，消费者订阅的消息通道
     *
     * @return
     */
    @Bean
    public MessageChannel mqttInboundChannel(MessageHandler mqttInboundHandler) {
        DirectChannel dc = new DirectChannel();
        dc.subscribe(mqttInboundHandler);
        return dc;
    }

    @Bean
    @ConditionalOnMissingBean
    public IMqttListener iMqttListener() {
        return new DefaultMqttListener();
    }

    /**
     * 使用@ServiceActivator注解，表明所修饰的方法用于消息处理
     * 使用inputChannel值，表明从指定通道中取值
     *
     * @return
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttInBoundChannel")
    public MessageHandler mqttInboundHandler(IMqttListener iMqttListener) {
        return message -> {
            IotMessage m = new IotMessage();
            m.setTopic(message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC).toString());
            m.setHeaders(message.getHeaders());
            Object payload = message.getPayload();
            m.setBody(payload.toString());

            // TODO 需要解密payload

            try {
                iMqttListener.consume(m);
            } catch (Exception var6) {
                log.error("ms mqttInboundHandler error class:{},method:{}, topic:{},message:{},error:{}", iMqttListener.getClass().getName(), "receiveMessage", m.getTopic(), m.getBody(), var6.getMessage());
            }

        };
    }

    /**
     * MQTT消息发布处理器绑定
     *
     * @return {@link MessageHandler}
     */
    @Bean
    @ServiceActivator(inputChannel = MqttConstant.CHANNEL_NAME_OUT)
    public MessageHandler mqttOutboundHandler() {
        // 初始化出站通道适配器，使用的是Eclipse Paho MQTT客户端库
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(clientProperties.getId() + "-" + this.profile + "-pub-" + Instant.now().toEpochMilli(), mqttClientFactory());
        messageHandler.setAsync(true);
        //设置服务质量：0 最多一次，数据可能丢失;1 至少一次，数据可能重复;2 只有一次，有且只有一次，最耗性能
        messageHandler.setDefaultQos(producerProperties.getDefaultQos());
        messageHandler.setDefaultRetained(producerProperties.getDefaultRetained());
        messageHandler.setConverter(new DefaultPahoMessageConverter());
        return messageHandler;
    }

    /**
     * MQTT消息订阅绑定
     */
    @Bean
    public MessageProducer getMqttConsumer(MessageChannel mqttInboundChannel) {
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(clientProperties.getId() + "-" + this.profile + "-sub", mqttClientFactory(), subscribeTopics());
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(consumerProperties.getDefaultQos());
        adapter.setOutputChannel(mqttInboundChannel);
        return adapter;
    }

    public String[] subscribeTopics() {

        List<String> topicList = new ArrayList<>();
        topicList.add(MqttConstant.SYS_TOPIC_CLIENT);
        if (consumerProperties.getTopics() != null) {
            topicList.addAll(Arrays.asList(consumerProperties.getTopics()));
        }
        for (int i = 0; i < topicList.size(); i++) {
            //系统主题不设置为共享订阅
            if (MqttConstant.SYS_TOPIC_CLIENT.equals(topicList.get(i))) {
                continue;
            }
            topicList.set(i, MqttConstant.SHARED_SUBSCRIBE_PREFIX + topicList.get(i));
        }
        return topicList.toArray(new String[topicList.size()]);
    }

}
